package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.heima.behavior.service.ReadService;
import com.heima.model.behavior.dtos.ReadDto;
import com.heima.model.behavior.pojos.ReadDoc;
import com.heima.model.common.dtos.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

@Service
public class ReadServiceImpl implements ReadService {
    /**
     * 用户行为——阅读
     * @param dto
     * @return
     */
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public ResponseResult readBehavior(ReadDto dto) {
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()));
        long count = mongoTemplate.count(query, ReadDoc.class);
        //判断是否有文章的阅读记录，如果有，阅读次数自增1
        if (count>0) {
            Update update = new Update().inc("count",1);
            mongoTemplate.updateFirst(query,update, ReadDoc.class);
            System.out.println("阅读次数+1");
            return ResponseResult.okResult();
        }
        //如果没有，就新增记录，阅读次数1
        else {
            ReadDoc readDoc = new ReadDoc(IdWorker.getId(), dto.getArticleId(), 1);
            mongoTemplate.save(readDoc);
            System.out.println("第一次阅读");
            return ResponseResult.okResult();
        }
//        Update update = new Update().set("count",dto.getCount()+1);
//        mongoTemplate.updateMulti(query,update,UserReadDoc.class);
//        System.out.println("阅读量+1");
//        return ResponseResult.okResult();
    }
}
